<template>
    <div id="app" class="with-bar tab-video" :class="{'page-loading':page.loading || initLoading}">
        <ui-loading v-if="initLoading" class="page-init-loading">
             <div slot="content"></div>
        </ui-loading>
        <scroll-fixed>
            <div class="ui-header">
                <div class="tabs">
                    <div class="tabs-wrap">
                        <ui-tabs ref="tabs" :list="channel.my" :active="page.channel_id" @choose="changeTab" @init="initTabs"/>
                    </div>
                    <a href="javascript:;" @click="channel.status = true" class="add-on">
                        <i class="uicon uicon-add"></i>
                    </a>
                </div>
            </div><!-- end ui-header -->
        </scroll-fixed>

        <ui-loading v-if="page.loading" />
        <page-error v-else-if="pageError" @refresh="pageRefresh"></page-error>
        <scroll-list v-else ref="scroll" class="ui-list" :class="{'no-data':page.is_end && news.list.length == 0}" :config="scroll" @pull="pullLoad" @bottom="loadmore">
             <div class="area-bar" v-if="this.page.country_short_name!== ''">
                <div class="wrap">
                    <a href="javascript:void(0);" @click="area.status = true" class="item">
                        <i class="uicon uicon-gps"></i><span>更多区域</span>
                    </a>
                    <div class="item">
                        <img :src="page.area.weather_icon"><span>{{page.area.weather_desc}}</span>
                    </div>
                </div>
            </div>
            <page-error v-if="page.is_end && news.list.length == 0">
                <div slot="logo">
                    <img src="../assets/page-empty.png" class="logo">
                </div>
                <div slot="text">
                    <p class="text">暂无内容</p>
                </div>
            </page-error>
            <transition-group v-else name="list" tag="div">
                <ui-item v-for="item in news.list" :item="item" :key="item.type + '_' +item.id" 
                :params="player" 
                @more="popupMore" 
                @playVideo="playVideo"
                @volumechange="volumeChange"></ui-item>
            </transition-group>
        </scroll-list><!-- en dui-list -->

        <offline :withbar="true"/>
        <ui-tab-bar :active="page.tabBarActive" @change="tabChange"></ui-tab-bar>
        <popup-channel ref="channel" v-if="channel.status" :config="channel" :type="'video'"  @done="channelChange" />
        <popup-more :status="moreConfig.status" :config="moreConfig" @report="report_status = true,moreConfig.status=false" @unlike="removeItem"  @close="moreConfig.status = false" @fav="changeFav" @night="changeNight"></popup-more>
        
        <ui-report v-if="report_status" :id="moreConfig.item.id" :type="moreConfig.item.type" :title="moreConfig.item.title" @cancel="reportCancel" @done="reportDone"/>
        <popup-area :status="area.status" :active="page.area" :list="channel" @done="areaDone" @close="area.status = false"></popup-area>
        
        <ui-popup :status="alert.status" @close="alert.status = false">
            <div class="ui-alert">
                <div class="alert-content">
                    <p>切换地区</p>
                    <span>检测到你在{{alert.name}},是否切换到该地区?</span>
                </div>
                <div class="alert-footer">
                    <a href="javascript:;" @click="cancel">取消</a>
                    <a href="javascript:;" @click="confirm">确定</a>
                </div>
            </div>
        </ui-popup>
        <slide-tool ref="slide" />
    </div>
</template>
<script>
import Area from "../components/area.vue";
import Items from '../components/items.vue'
import ScrollList from '../components/scrollList.vue'
import pageBar from '../components/pagebar.vue'
import scrollFixed from '../components/scrollFixed.vue'
import moreBox from '../components/morebox.vue'
import pageError from '../components/pageError.vue'
import offline from '../components/offline.vue'
import UILoading from '../components/loading.vue'
import UIPopup from "../components/popup.vue";

import mxNavTab from '../mixins/navtab.js'
import mxTabBar from '../mixins/tabbar.js'
import mxReport from '../mixins/report.js'
import mxSlide from "../mixins/slide.js";
export default {
    name:'tab-video',
    data(){
        return {
            page:{
                tabBarActive:1,
                cache_channel_type:'video_channel',
                is_end:false,//是否已经没有数据
                page_no:1,
                channel_id:'',
                country_short_name:'',
                loading:true,
                area:{}
            },
            player:{
                muted:false,
                active:''
            },
            area: {
                status: false
            },
            pageError:false,
            initLoading:true,
            moreConfig:{
                id:'',
                status:false,
                fav:false,
                night:false,
                item:''
            },
            news:{
                list:[]
            },
            scroll:{
                pull:false,
                bottom:false,
            },
            pullType: 'down'
        }
    },
    mixins: [mxNavTab,mxTabBar,mxReport,mxSlide],
    components:{
        [Area.name]: Area,
        [Items.name]:Items,
        [scrollFixed.name]:scrollFixed,
        [ScrollList.name]:ScrollList,
        [offline.name]:offline,
        [UILoading.name]:UILoading,
        [pageError.name]:pageError,
        [moreBox.name]:moreBox,
        [UIPopup.name]: UIPopup,
    },
    mounted(){
        this.$on("RELOADDATA",type=>{
            this.$emit('PLYAER_CLOSE');
            this.page.page_no = 1;
            this.page.loading = true;
            this.page.is_end = false;
            this.scroll.bottom = false;

            this.loadPageData(true).then(rs=>{
                this.$nextTick(()=>{
                    //当第一页小于等于3跳数据时，当作pageend处理
                    this.scroll.bottom = this.news.list.length <= 3 ? 'hidden' : false;
                })
            }).catch(e=>{
                this.pageError = true;
            }).finally(()=>{
                this.$nextTick(()=>{
                    this.initLoading = false;
                    this.page.loading = false;
                })
            })
        });

        window.addEventListener('scroll',()=>{
            if(this.player.active){
                let rect = this.player.active.getBoundingClientRect();
                if(rect.top < 0 && Math.abs(rect.top) >= rect.height || rect.top >= window.innerHeight){
                    this.player.active.pause();
                }
            }
        });
    },
    methods:{
        volumeChange(e){
            this.player.muted = e.currentTarget.muted;
        },
        playVideo(e,item){
            if(item.play_status == 0){
                item.play_status = 1;
            }
            this.$el.querySelectorAll('video').forEach(item=>{
                item.pause();
                item.currentTime = 0;
            })
            let video = e.currentTarget.parentNode.querySelector('video');
            video.play();
            this.player.active = video;
        },
        loadPageData(needClean = false,isUnshift = false,loadPageData = false){
            let url ,params = {
            }

            let pchannel = [],
                pcounry = [];

            this.channel.my.forEach(item=>{
                if(item.short_name){
                    pcounry.push(item.short_name);
                }else{
                    pchannel.push(item.id);
                }
            })
            if(this.page.channel_id===0){
                params.is_main=1;
            }else{
                if (this.page.channel_id === "") {//选中了地区
                    if(pchannel.length>0) params.filter_channels = pchannel.join(',');
                    params.country = this.page.country_short_name
                }

                if (this.page.country_short_name === "") {//选中频道
                if(pcounry.length>0) params.filter_countrys = pcounry.join(',');
                params.channel = this.page.channel_id;
                }
            }
           
            if(loadPageData!= "isRefresh"){
                params.action='refresh';
            }
        
            url = '?ct=news&ac=get_list';
            params.type = 2; 
            params.pull = this.pullType;

            // if (this.page.channel_id === 0) {
            //     params.is_home_page = 1;
            // }
         
            return this.$http.get(url,{params}).then(response=>{
                let {data} = response;
                if(needClean) this.news.list = [],document.body.scrollTop = 0;
                if(data.code == 0){
                    this.page.is_end = !data.data.is_have_data;
                    let list = [];
                    data.data.list && data.data.list.forEach && data.data.list.forEach(item=>{
                        if(this.$utils.unlike.check(item.id)) return;
                        let tmpItem = item;
                        tmpItem.url = item.detail_url;
                        tmpItem.type = 'video-item';
                        tmpItem.src = item.cover_img[0];
                        tmpItem.play_status = 0;
                        tmpItem.source = {
                            name:item.source
                        }
                        tmpItem.view = item.browse_total;
                        tmpItem.time = this.$moment(item.issue_time * 1000).fromNow().replace(' ','');
                        if(!item.is_hot && item.style_num != 1){
                            tmpItem.close = true;
                        }
                        list.push(tmpItem)
                    })

                    if(!needClean){
                        if(isUnshift){
                            let savelist = [];
                            this.news.list.forEach(item=>{
                                if(item.is_top !== 1 && item.is_hot !== 1){
                                    savelist.push(item); 
                                }
                            })
                            this.news.list = list.concat(savelist);
                            return data.data.count
                        }else{
                           let savelist = [];
                            list.forEach(item=>{
                                if(item.is_top !== 1 && item.is_hot !== 1){
                                    savelist.push(item); 
                                }
                            })
                            this.news.list = this.news.list.concat(savelist);
                        }
                    }else{
                        this.news.list = list;
                    }
                    
                    this.page.page_no++;

                    if(params.action == 'refresh') {
                        let pagePosition = this.$utils.caches.get('pagePosition', 'session');
                        setTimeout(() => {
                            scrollTo(0, pagePosition ? pagePosition : 0);
                            this.$utils.caches.set('pagePosition', 0, 'session');
                        }, 10);
                    }
                    return data.data.count
                }else{
                    this.$toast(data.msg);
                }
            }).catch(err=>{
                window.$zEvent.$emit('ERROR',err);
                this.$toast(err);
            })
          
        },
        pullLoad(cb){
           this.pullType = 'down';
           this.scroll.bottom = false;
           this.player.active && this.player.active.pause();
           this.loadPageData(false,true,"isRefresh").then((count)=>{
                this.$nextTick(() => {
                    //当第一页小于等于3跳数据时，当作pageend处理
                    this.scroll.bottom = this.news.list.length <= 3 ? 'hidden' : false;
                    this.$refs.scroll && this.$refs.scroll.$emit('refresh_done',count)
                    cb && cb()
                });
            })
        },
        loadmore(){
            if(this.scroll.bottom) return false;
            this.pullType = 'up';
            this.scroll.bottom = true;
            this.loadPageData("","","isRefresh").then((num)=>{
                this.$nextTick(() => {
                    this.scroll.bottom = num === 0 ? 'done' : false;
                });
            })
        },
        popupMore(item){
            this.moreConfig.id = item.id;
            this.moreConfig.item = item;
            this.moreConfig.fav = !!item.is_collect;
            this.moreConfig.night = false;
            this.moreConfig.status = true;
        },
        changeFav(flag){
            this.moreConfig.fav = flag;
            this.moreConfig.item.is_collect = flag ? 1 : 0
            this.moreConfig.status = false;
        },
        changeNight(flag){
            this.moreConfig.night = flag;
            this.moreConfig.status = false;
             
        },
        pageRefresh(){
            this.pageError = false;
            this.$emit('RELOADDATA');
        },
        removeItem() {
            let item = this.moreConfig.item;
            let idx = this.news.list.indexOf(item);
            this.news.list.splice(idx, 1);
        },
        areaDone(item) {
            if(item.short_name !== this.page.area.short_name){
                for(let i = 0,len = this.channel.my.length;i<len;i++){
                    let channel = this.channel.my[i];
                    if(channel.short_name == this.page.area.short_name){
                        this.channel.my.splice(i,1,item);
                        this.page.area = item;
                        this.page.country_short_name = item.short_name;
                        this.updateTabData(this.channel.my);
                        this.$nextTick(()=>{
                            this.$emit('RELOADDATA','channelChange');
                        })
                        break;
                    }
                }
            }
            this.area.status = false;
        },
    }
}
</script>
<style lang="less">
.tab-video {
    .video-item + .video-item {
        margin-top:12px;
    }
    .ui-list.no-data {
        flex:1;
        display: flex;
        flex-direction: column;
    }
    .ui-alert {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 600px;
    height: 330px;
    background: #fff;
    z-index: 999;
    transform: translate(-50%, -50%);
    border-radius: 10px;
    .alert-content {
        text-align: center;
        padding: 30px;
        p {
            margin: 15px auto 35px;
            font-size: 36px;
            font-weight: 500;
            color: #282828;
        }
        span {
            line-height: 1.2;
            font-size: 32px;
            color: #666;
        }
    }

    .alert-footer {
        position: absolute;
        bottom: 0;
        width: 100%;
        display: flex;
        a {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 81px;
            width: 50%;
            text-align: center;
            font-size: 36px;
            border-top: 1px solid #e2e2e2;
            color: #666;

            &:last-child {
                color: #e64a19;
            }

            & + a {
                border-left: 1px solid #e2e2e2;
            }
        }
    }
}

}
</style>


